package com.qingcheng.mq;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SpuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:boy
 * @Date:2019/7/25
 * @description:
 * @ModifiedBy:
 */
@Component
public class GoodsAddPageConsumer implements MessageListener {
    private Logger logger = LoggerFactory.getLogger(GoodsAddPageConsumer.class);
    @Reference
    private SpuService spuService;
    @Reference
    private CategoryService categoryService;
    @Autowired
    private TemplateEngine templateEngine;
    @Value("${pagePath}")
    private String pagePath;

    public void onMessage(Message message) {
        try {
            String id = new String(message.getBody(), "utf-8");
            this.addPage(id);
        } catch (UnsupportedEncodingException e) {
            logger.error("消息编码异常", e);
        }
    }

    /**
     * 根据spuId 生成商品详情页
     *
     * @param id
     */
    private void addPage(String id) {
        Goods goods = spuService.findGoodsBySpuId(id);
        //未查询到商品
        if (goods == null) {
            return;
        }
        Spu spu = goods.getSpu();
        List<Sku> skuList = goods.getSkuList();
        if (spu != null && skuList != null && skuList.size() > 0) {
            //路径数据封装对象
            Map urlMap = new HashMap();
            for (Sku sku : skuList) {
                if ("1".equals(sku.getStatus())) {//对规格参数排序
                    String specStr = JSON.toJSONString(JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);
                    urlMap.put(specStr, sku.getId() + ".html");
                }
                Context context = new Context();
                //模型数据封装对象
                Map<String, Object> model = new HashMap<String, Object>();
                model.put("spu", spu);
                model.put("sku", sku);
                //分类信息
                List<String> categoryList = new ArrayList<String>();
                categoryList.add(categoryService.findById(spu.getCategory1Id()).getName());
                categoryList.add(categoryService.findById(spu.getCategory2Id()).getName());
                categoryList.add(categoryService.findById(spu.getCategory3Id()).getName());
                model.put("categoryList", categoryList);
                //图片
                model.put("skuImage", sku.getImage());
                model.put("skuImages", sku.getImages().split(","));
                model.put("spuImages", spu.getImages().split(","));
                //规格参数
                Map paramItems = JSON.parseObject(spu.getParaItems());
                model.put("paramItems", paramItems);
                Map specItems = JSON.parseObject(sku.getSpec());
                model.put("specItems",specItems);
                //规格面板
                Map<String,List> specMap=(Map) JSON.parseObject(spu.getSpecItems());
                for (String key : specMap.keySet()) {
                   List<String> list=specMap.get(key);
                   List<Map> mapList=new ArrayList<Map>();
                    for (String value : list) {
                       Map map=new HashMap();
                       map.put("option",value);
                       //商品详细url
                        Map spec=JSON.parseObject(sku.getSpec());
                        spec.put(key,value);
                        String jsonSpec = JSON.toJSONString(spec, SerializerFeature.MapSortField);
                        map.put("url",urlMap.get(jsonSpec));
                        //判断是否是当前商品
                        if (value.equals(specItems.get(key))){
                            map.put("checked",true);
                        }else {
                            map.put("checked",false);
                        }
                        mapList.add(map);
                    }
                    specMap.put(key,mapList);
                }
                model.put("specMap",specMap);
                //填充模型数据
                context.setVariables(model);
                //生成文件位置
                File file=new File(pagePath);
                if (!file.exists()){
                    file.mkdirs();
                }
                try {
                    File destFile=new File(file,sku.getId()+".html");
                    PrintWriter printWriter=new PrintWriter(destFile,"UTF-8");
                    templateEngine.process("item",context,printWriter);
                } catch (FileNotFoundException e) {
                    logger.error("模板页面生成出错",e);
                } catch (UnsupportedEncodingException e) {
                    logger.error("模板页面生成出错",e);
                }
            }
        }
    }
}
